package com.etone.smartAudit.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etone.smartAudit.domain.ServerDisk;
import com.etone.smartAudit.domain.ServerInfo;
import com.etone.smartAudit.enums.StateType;
import com.etone.smartAudit.mapper.ServerDiskMapper;
import com.etone.smartAudit.mapstruct.ServerDiskMapStruct;
import com.etone.smartAudit.utils.ElasticSearchUtil;
import com.etone.smartAudit.utils.ElasticUtil;
import com.etone.smartAudit.vo.serverInfo.serverDisk.ServerDiskVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: sovy
 * @date: 2020/10/22
 * @description:
 */
@Slf4j
@Service
@AllArgsConstructor
public class ServerDiskService extends ServiceImpl<ServerDiskMapper, ServerDisk> {

    private ElasticSearchUtil elasticSearchUtil;

    private ServerDiskMapStruct serverDiskMapStruct;

    /**
     * 通过服务器id获取磁盘信息
     *
     * @param serverId 服务器id
     * @return
     */
    public List<ServerDisk> findByServerId(Integer serverId) {
        return baseMapper.findByServerId(serverId);
    }

    /**
     * 搜集磁盘盘符信息
     */
    public void collectDisk(ServerInfo serverInfo) {
        String target = "filesystem";
        List<ServerDisk> serverDisks = findByServerId(serverInfo.getId());
//        if (!CollectionUtils.isEmpty(serverDisks)) {
        serverDisks.forEach(serverDisk -> {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder
                    .must(QueryBuilders.matchQuery("metricset.name", target).operator(Operator.AND))
                    .must(QueryBuilders.matchQuery("system.filesystem.mount_point", serverDisk.getMount()).operator(Operator.AND))
                    .must(QueryBuilders.matchQuery("fields.ip", serverInfo.getIp()).operator(Operator.AND));
            SearchSourceBuilder searchSourceBuilder = ElasticUtil.initSearchSourceBuilder(boolQueryBuilder, 0, 1, 60);
            searchSourceBuilder.fetchSource(new String[]{"system", "host", "@timestamp"}, null);
            searchSourceBuilder.sort("@timestamp", SortOrder.DESC);
            log.info("查询{}服务器盘符{}条件:{}", serverInfo.getName(), serverDisk.getMount(), searchSourceBuilder.toString());
            List<JSONObject> datas = elasticSearchUtil.search(serverInfo.getEsInfo().getIndex(), searchSourceBuilder, JSONObject.class);
            if (!CollectionUtils.isEmpty(datas)) {
                JSONObject dataInfoJson = datas.get(0);
                log.info("查询{}服务器盘符{}结果:{}", serverInfo.getName(), serverDisk.getMount(), dataInfoJson.toJSONString());
                //获取盘符大小
                Double total = dataInfoJson.getJSONObject("system").getJSONObject("filesystem").getDouble("total");
                //获取盘符剩余大小
                Double free = dataInfoJson.getJSONObject("system").getJSONObject("filesystem").getDouble("free");
                if (total != null && total != 0d) {
                    serverDisk.setSpace(total / Math.pow(1024, 3));
                    serverDisk.setUsedSpace((total - free) / Math.pow(1024, 3));
                    this.baseMapper.updateSpace(serverDisk);
                }
            } else {
                log.warn("未查到{}服务器盘符{}信息", serverInfo.getName(), serverDisk.getMount());
            }
        });
//        }

    }

    /**
     * 盘符列表
     *
     * @param serverId
     * @return
     */
    public List<ServerDiskVO> list(Integer serverId) {
        List<ServerDisk> serverDisks = baseMapper.findByServerId(serverId);
        if (!CollectionUtils.isEmpty(serverDisks)) {
            return serverDiskMapStruct.getServerDiskVO(serverDisks);
        }
        return null;
    }
}
